package com.sgb.kjwl.view.ui.activity.self.logistics;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityOrdinaryCargoPublishDateBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.utils.CargoConstant;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.widget.transport.CargoTimePickerView;
import com.sgb.kjwl.viewmodel.transport.CargoPublishDateViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.TimeUtil;

import java.util.Calendar;
import java.util.Date;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 2021/6/22 09:53
 * @Description: 普通货源发布填写装货时间页面
 */
public class OrdinaryCargoPublishDateActivity extends AppActivity {

    @Inject
    CargoPublishDateViewModel viewModel;
    ActivityOrdinaryCargoPublishDateBinding binding;
    //是否是开始时间
    private boolean mIsBegin;
    //时间选择器
    private CargoTimePickerView mTimePicker;
    //数据实体类
    private CargoPublishEntity mEntity;

    public static void start(Activity activity, CargoPublishEntity entity, int requestCode) {
        Intent intent = new Intent(activity, OrdinaryCargoPublishDateActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(RouterKey.DATA, entity);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(CargoPublishDateViewModel.class);
    }

    @Override
    protected void init() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_ordinary_cargo_publish_date);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("装货时间");
        initPicker();
        initEvent();
        initData();
    }

    private void initPicker() {
        mTimePicker = PickerHelper.with(this).getCargoTimeBuild("", (date, v) -> {
            if (mIsBegin) {
                checkBeginTime(date);
            } else {
                checkEndTime(date);
            }
        })
                .setRangDate(Calendar.getInstance(), null)
                .build();
        mTimePicker.setOnDismissListener(o -> clearAllFocus());
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.includeTitle.ivBack.setOnClickListener(this);
    }

    private void initData() {
        mEntity = getIntent().getParcelableExtra(RouterKey.DATA);
        if (mEntity == null) {
            mEntity = new CargoPublishEntity();
        } else {
            syncData();
        }
    }

    private void syncData() {
        if (mEntity.getBeginTime() != 0) {
            binding.tvReleaseCargoStartTime.setText(CargoConstant.stampFormatLoadInput(mEntity.getBeginTime(), mEntity.getStartPointTime()));
            binding.tvCloseStart.setVisibility(View.VISIBLE);
        }
        if (mEntity.getEndTime() != 0) {
            binding.tvReleaseCargoEndTime.setText(CargoConstant.stampFormatLoadInput(mEntity.getEndTime(), mEntity.getEndPointTime()));
            binding.tvCloseEnd.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 检查设置开始时间
     */
    private void checkBeginTime(Date date) {
        long time = date.getTime();
        String[] beginTime = formatTime(time);
        //设置时间点
        int point = NumberUtil.convertToInt(beginTime[1]);
        if (point == 0) {
            mEntity.setBeginTime(DateUtils.getCustomizeDayMorning(0, time).getTime());
            mEntity.setStartPointTime(25);
        } else {
            mEntity.setBeginTime(time);
            mEntity.setStartPointTime(point);
        }
        binding.tvReleaseCargoStartTime.setText(CargoConstant.stampFormatLoadInput(mEntity.getBeginTime(), mEntity.getStartPointTime()));
        binding.tvCloseStart.setVisibility(View.VISIBLE);
    }

    /**
     * 检查设置结束时间
     */
    private void checkEndTime(Date date) {
        long time = date.getTime();
        String[] endTime = formatTime(time);
        //设置时间点
        int point = NumberUtil.convertToInt(endTime[1]);
        if (point == 0) {
            mEntity.setEndTime(DateUtils.getCustomizeDayNight(0, time).getTime());
            mEntity.setEndPointTime(25);
        } else {
            mEntity.setEndTime(time);
            mEntity.setEndPointTime(point);
        }
        binding.tvReleaseCargoEndTime.setText(CargoConstant.stampFormatLoadInput(mEntity.getEndTime(), mEntity.getEndPointTime()));
        binding.tvCloseEnd.setVisibility(View.VISIBLE);
    }

    /**
     * 格式化时间，拆分比较
     */
    private String[] formatTime(long time) {
        String timeStr = DateUtils.formatDate(time, "yyyyMMdd HH");
        String[] times = timeStr.split(" ");
        if (times.length == 2) {
            return times;
        } else {
            return new String[2];
        }
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        if (v == binding.includeTitle.ivBack) {
            finish();
        } else if (v == binding.llReleaseCargoStartTime) {
            mIsBegin = true;
            mTimePicker.setTitleText("选择装货开始时间");
            mTimePicker.show();
        } else if (v == binding.llReleaseCargoEndTime) {
            mIsBegin = false;
            mTimePicker.setTitleText("选择装货结束时间");
            mTimePicker.show();
        } else if (v == binding.tvReleaseCargoSubmit) {
            clearAllFocus();
            checkData();
        }else if (v==binding.tvCloseStart){
            binding.tvReleaseCargoStartTime.setText("");
            mEntity.setBeginTime(null);
            mEntity.setStartPointTime(null);
            binding.tvCloseStart.setVisibility(View.GONE);
        }else if (v==binding.tvCloseEnd){
            binding.tvReleaseCargoEndTime.setText("");
            mEntity.setEndTime(null);
            mEntity.setEndPointTime(null);
            binding.tvCloseEnd.setVisibility(View.GONE);
        } else if (v == binding.llReleaseCargoStartTime) {
            mIsBegin = true;
            mTimePicker.setTitleText("选择装货开始时间");
            mTimePicker.show();
        } else if (v == binding.llReleaseCargoEndTime) {
            mIsBegin = false;
            mTimePicker.setTitleText("选择装货结束时间");
            mTimePicker.show();
        }
    }

    /**
     * 检查数据并回传
     */
    private void checkData() {
        if (mEntity == null) return;
        if (mEntity.getBeginTime() == 0) {
            MToast.showToast(this, "请选择装货开始时间");
            return;
        }
        //判断结束时间
        if (mEntity.getEndTime() != 0) {
            if (mEntity.getBeginTime() > mEntity.getEndTime()) {
                MToast.showToast(this, "装货结束时间不能小于装货开始时间");
                return;
            }
            //间隔时间（31天内
            long INTERVALS = 31L * 24L * 60L * 60L * 1000L;
            //判断间隔时间
            if (mEntity.getEndTime() - mEntity.getBeginTime() > INTERVALS) {
                MToast.showToast(this, "装货开始时间与装货结束时间间隔最大30天");
                return;
            }
            //判断两个时间年月日的时间戳相等
            if (DateUtils.getCustomizeDayNight(0, mEntity.getBeginTime()).getTime()==DateUtils.getCustomizeDayNight(0, mEntity.getEndTime()).getTime()){
                if (mEntity.getStartPointTime()==25&&mEntity.getEndPointTime()!=25){
                    MToast.showToast(this, "装货结束时间不能小于装货开始时间");
                    return;
                }
                if (mEntity.getStartPointTime()!=25&&mEntity.getEndPointTime()!=25&&mEntity.getStartPointTime()>=mEntity.getEndPointTime()){
                    MToast.showToast(this, "装货结束时间不能小于装货开始时间");
                    return;
                }
                if (mEntity.getEndTime()<TimeUtil.currentTimeMillis()){
                    MToast.showToast(this, "装货结束时间不能小于当前时间");
                    return;
                }
                if (mEntity.getStartPointTime()==25?DateUtils.getCustomizeDayNight(0,mEntity.getBeginTime()).getTime()<DateUtils.getCustomizeDayNight(0,TimeUtil.currentTimeMillis()).getTime():mEntity.getBeginTime()<TimeUtil.currentTimeMillis()){
                    MToast.showToast(this, "装货开始时间不能小于当前时间");
                    return;
                }
            }else {
                if (mEntity.getEndTime()<TimeUtil.currentTimeMillis()){
                    MToast.showToast(this, "装货结束时间不能小于当前时间");
                    return;
                }
                if (mEntity.getStartPointTime()==25?DateUtils.getCustomizeDayNight(0,mEntity.getBeginTime()).getTime()<DateUtils.getCustomizeDayNight(0,TimeUtil.currentTimeMillis()).getTime():mEntity.getBeginTime()<TimeUtil.currentTimeMillis()){
                    MToast.showToast(this, "装货开始时间不能小于当前时间");
                    return;
                }
            }
        }else {
            if (mEntity.getStartPointTime()==25?DateUtils.getCustomizeDayNight(0,mEntity.getBeginTime()).getTime()<DateUtils.getCustomizeDayNight(0,TimeUtil.currentTimeMillis()).getTime():mEntity.getBeginTime()<TimeUtil.currentTimeMillis()){
                MToast.showToast(this, "装货开始时间不能小于当前时间");
                return;
            }
        }
        Intent intent = new Intent();
        intent.putExtra(RouterKey.DATA, mEntity);
        setResult(RESULT_OK, intent);
        finish();
    }
}
